<script setup lang="ts">
import { h, onMounted, ref, reactive } from "vue";

import {
  NButton,
  NText,
  NPopconfirm,
  zhCN,
  dateZhCN,
  useMessage,
} from "naive-ui";
import { userclassifyStore } from "@/stores/classify";
const classifyStore = userclassifyStore();

// 表格高度自适应
let autoTableHeight = ref(null);
const autuHeight = (height) => {
  autoTableHeight.value = window.innerHeight - height;
  window.onresize = () => {
    autoTableHeight.value = window.innerHeight - height;
  };
  return autoTableHeight.value;
};

import { getTableHright } from "@/utils/autoHeight";
const { getHeight } = getTableHright(420);

// 表格
const sort = reactive({
  title: "排序",
  key: "sort",
  align: "center",
  sorter: true,
  sortOrder: false,
});
const columns = [
  {
    title: "编号",
    key: "no",
    align: "center",
    render: (_: any, index: number) => {
      return `${index + 1}`;
    },
  },
  {
    title: "分类名称",
    key: "name",
    align: "center",
  },
  {
    title: "商品数量",
    key: "length",
    align: "center",
    render() {
      return h(NText, {}, { default: () => "1000" });
    },
  },
  {
    title: "导航栏",
    key: "length",
    align: "center",
    render() {
      return h(NText, {}, { default: () => "不显示" });
    },
  },
  {
    title: "是否显示",
    key: "status",
    align: "center",
  },
  sort,
  {
    title: "操作",
    key: "length",
    align: "center",
    render(row: any) {
      return [
        h(
          NButton,
          {
            strong: true,
            tertiary: true,
            size: "small",
            type: "primary",
            onClick: () => play(row),
          },
          { default: () => "修改" }
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => positiveClick(row),
            onNegativeClick: () => negativeClick(),
            negativeText: "取消",
            positiveText: "确定",
          },
          {
            trigger: () =>
              h(
                NButton,
                {
                  strong: true,
                  tertiary: true,
                  size: "small",
                  type: "success",
                  style: {
                    marginLeft: "20px",
                  },
                },
                { default: () => "删除" }
              ),
            default: () => h("span", {}, "你确定要删除吗？？？"),
          }
        ),
      ];
    },
  },
];
const options = [];

// 渲染列表
onMounted(() => {
  classifyStore.getLIst();
});

// 点击新建弹出   模态框
const showModal = ref();
const showModul = () => {
  showModal.value = true;
};

//表单验证
const rules = {
  name: {
    required: true,
    trigger: ["blur", "input"],
    message: "测试内容更改",
  },
  sort: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入排序的数字",
  },
  status: {
    required: true,
    trigger: ["blur", "input"],
    message: "请选择显示状态",
  },
};

const formRef = ref(null);
// 表单
const form = reactive({
  name: "",
  sort: "",
  status: "",
});

// 点击确认按钮   新增数据
const onPositiveClick = async () => {
  formRef.value?.validate(async (errors: any) => {
    if (!errors) {
      await classifyStore.doAdd({ ...form });
      await classifyStore.getLIst();
      (form.name = ""),
        (form.sort = ""),
        (form.status = ""),
        (showModal.value = false);
    }
  });
};

// 点击取消按钮   清空表单
const onNegativeClick = () => {
  (form.name = ""),
    (form.sort = ""),
    (form.status = ""),
    (showModal.value = false);
};

// 删除
const positiveClick = async (row: any) => {
  await classifyStore.doDelete(row._id);
  if (classifyStore.list.length == 1) {
    Pages(classifyStore.page - 1);
  } else {
    classifyStore.getLIst();
  }
};

// 取消按钮
const message = useMessage();
const negativeClick = () => {
  message.warning("您已取消删除");
};

// 搜索
const seacrh = ref();
const seacrhs = async () => {
  classifyStore.page = 1;
  await classifyStore.getLIst(seacrh.value);
};
// 分页
const Pages = (page: number) => {
  // 拿到当前页
  classifyStore.page = page;
  classifyStore.getLIst(seacrh.value);
};
const PageSizes = (pageSize: number) => {
  classifyStore.pageSize = pageSize;
  classifyStore.page = 1;
  classifyStore.getLIst(seacrh.value);
};

// 修改
const play = (row) => {
  console.log(row);
  showModal.value = true;
  Object.assign(form, { ...row });
};

// 排序
const handleSorterChange = async (sorter: any) => {
  sort.sortOrder = !sorter ? false : sorter.order;
  // 通过$patch 改变  stores 里的值
  classifyStore.$patch({
    by: sorter.columnKey,
    order: sorter.order,
  });
  classifyStore.getLIst(seacrh.value);
};

// 搜索框失去焦点事件
const selectBlur = () => {
  classifyStore.getLIst();
};
</script>

<template>
  <n-layout>
    <n-layout-header>菜品分类</n-layout-header>
    <n-layout-footer>
      <n-layout has-sider>
        <n-layout>
          <n-layout has-sider class="text">
            菜品分类：
            <n-input v-model:value="seacrh" type="text" clearable="true" @clear="selectBlur" placeholder="请输入需要搜索的菜系" />
          </n-layout>
        </n-layout>
        <n-button type="tertiary" @click="seacrhs"> 查询 </n-button>
      </n-layout>
    </n-layout-footer>
  </n-layout>
  <!-- 表格 -->
  <n-layout embedded content-style="padding-top: 24px;">
    <n-layout-content content-style="padding: 20px;">
      <n-layout has-sider>
        <n-layout style="color: blue">
          分类数量：{{ classifyStore.total }}个
        </n-layout>
        <n-button type="info" @click="showModul" dashed> 新建 </n-button>
      </n-layout>
    </n-layout-content>
  </n-layout>

  <n-data-table :style="{ height: `${getHeight}px` }" style="position: relative; bottom: 10px" :bordered="false"
    :striped="true" :columns="columns" :data="classifyStore.list" @update:sorter="handleSorterChange" striped
    :scroll-y="1800" :max-height="autuHeight(416)" />
  <!-- 分页 -->
  <n-config-provider :locale="zhCN" :date-locale="dateZhCN">
    <n-space justify="end" style="top: 52px; position: relative">
      <n-pagination v-model:page="classifyStore.page" v-model:page-size="classifyStore.pageSize"
        :page-sizes="[3, 5, 7, 10]" :item-count="classifyStore.total" @update:page="Pages" @update:page-size="PageSizes"
        show-quick-jumper show-size-picker />
    </n-space>
  </n-config-provider>
  <!-- 弹出 -->
  <n-modal v-model:show="showModal" preset="dialog" :title="form._id ? '修改分类' : '新增分类'" :showIcon="false"
    :onClose="onNegativeClick">
    <n-form ref="formRef" :model="form" :rules="rules" :size="size" label-placement="left" label-width="auto"
      class="form-width">
      <n-grid :cols="24" :x-gap="24">
        <n-form-item-gi :span="24" label="分类名称" path="name">
          <n-input v-model:value="form.name" placeholder="" />
        </n-form-item-gi>
        <n-form-item-gi :span="24" label="排序" path="sort">
          <n-input type="number" v-model:value="form.sort" placeholder="" />
        </n-form-item-gi>
        <n-form-item-gi :span="24" label="是否显示" path="status">
          <n-radio-group v-model:value="form.status" name="radiogroup1">
            <n-space>
              <n-radio value="是">显示</n-radio>
              <n-radio value="否">隐藏</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item-gi>

        <n-form-item-gi :span="14" style="justify-self: center">
          <n-button type="default" @click="onNegativeClick"> 取消 </n-button>
          <n-button type="info" @click="onPositiveClick"> 确认 </n-button>
        </n-form-item-gi>
      </n-grid>
    </n-form>
  </n-modal>
</template>

<style scoped>
html {
  background-color: #c0c0c0;
}

.n-layout-header {
  background-color: #e9eff5;
  height: 45px;
  padding: 15px;
}

.n-layout-footer {
  padding: 24px;
  background-color: #fff;
  padding-left: 50px;
}

.text {
  line-height: 33px;
}

button.n-button.n-button--info-type.n-button--medium-type {
  margin: 0 20px;
}

.n-select {
  margin-top: 0px;
  width: 200px;
}

.n-input {
  width: 200px;
}

.n-layout-sider {
  background: rgba(128, 128, 128, 0.3);
}

.form-width {
  padding: 20px 0 0 45px;
}
</style>
